package com.company.sort;

import java.util.Random;

/**
 * @author shenhan
 * @create 2020/2/1 18:28
 * @description
 */
public class MergeSort {
    public static void main(String[] args) {
        int[] arr = new int[80000];
        Random random = new Random();
        for (int i = 0; i < 80000; i++) {
            arr[i] = random.nextInt();
        }
        int[] temp = new int[arr.length];
        final long l1 = System.currentTimeMillis();
        breakArr(arr, 0, arr.length - 1, temp);
        final long l2 = System.currentTimeMillis();
        System.out.println(l2 - l1);
    }

    private static void breakArr(
            int[] arr, int left, int right, int[] temp) {
        if (left < right) {
            int mid = (left + right) / 2;
            breakArr(arr, left, mid, temp);
            breakArr(arr, mid + 1, right, temp);
            merge(arr, left, mid, right, temp);
        }
    }


    private static void merge(int[] arr, int left, int mid, int right, int[] temp) {
        //左边有序序列初始索引
        int i = left;
        //右边有序序列的初始索引
        int j = mid + 1;
        int t = 0;
        //先把左右两边有序数据按照规则填充到temp直到左右两边有一方处理完毕
        while (i <= mid && j <= right) {
            if (arr[i] <= arr[j]) {
                temp[t] = arr[i];
                t += 1;
                i += 1;
            } else {
                temp[t] = arr[j];
                t += 1;
                j += 1;
            }
        }
        //把剩余的填充入temp
        while (i <= mid) {
            temp[t] = arr[i];
            t += 1;
            i += 1;
        }
        while (j <= right) {
            temp[t] = arr[j];
            t += 1;
            j += 1;
        }
        //拷贝最后一次temp数据
        t = 0;
        int tempLeft = left;
        while (tempLeft <= right) {
            arr[tempLeft] = temp[t];
            t += 1;
            tempLeft += 1;
        }
    }
}
